<template>
    <div class="table-container" v-loading="loading">
        <div id="printTable">
            <h3 style="text-align: center">凉山州第一人民医院ICU危重症患者APACHE II评分登记表</h3>
            <div class="operate">
                <div style=" margin-right: 20px">
                    <el-date-picker v-model="selectedYear" type="daterange" range-separator="至" start-placeholder="开始时间"
                        end-placeholder="结束时间" style="width: 300px;" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD HH:mm:ss" :default-time="[
                            new Date(2000, 1, 1, 0, 0, 0),
                            new Date(2000, 1, 1, 23, 59, 59)
                        ]" />
                    <el-button @click="handleYearChange" style="margin-left: 20px;">
                        统计
                    </el-button>
                </div>
                <el-button type="primary" @click="handleExportExcel">
                    导出数据
                </el-button>
            </div>
            <table class="bordered-table">
                <!-- 第一行表头 -->
                <thead class="header">
                    <tr>
                        <template v-for="(header, index) in headers" :key="index">
                            <th :style="{ width: header.width }">
                                {{ header.title }}
                            </th>
                        </template>
                    </tr>
                </thead>
                <!-- 表格内容 -->
                <tbody>
                    <tr v-for="(item, rowIndex) in tableData" :key="rowIndex">
                        <td v-for="(value, key) in item" :key="key" :style="value?.width">
                            <span>{{ value }}</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { getApacheAPI, uploadAPI } from "../api/book.js";
import { writeFile, utils } from "xlsx";
import * as XLSX from 'xlsx';
import dayjs from "dayjs";
import { ElMessage } from 'element-plus';

const state = reactive({
    // selectedYear: [dayjs().format("YYYY-MM-DD HH:mm:ss"), dayjs().format("YYYY-MM-DD HH:mm:ss")],
    selectedYear:[],
    tableData: [],
    loading: false,
    show: false,
    docId: "",
    headers: [
        {
            title: "入科时间",
            key: "INTIME",
            width: "200px", // 设置列宽
        },
        {
            title: "入科后X小时(h)",
            key: "SCOREDIFF",
            width: "200px", // 设置列宽
        },
        {
            title: "姓名",
            key: "NAME",
            width: "180px", // 设置列宽
        },
        {
            title: "性别",
            key: "SEX",
            width: "80px", // 设置列宽
        },
        {
            title: "年龄(岁)",
            key: "AGE",
            width: "100px", // 设置列宽
        },
        {
            title: "床号",
            key: "BedName",
            width: "100px", // 设置列宽

        },
        {
            title: "住院号",
            key: "AdmissionNumber",
            width: "100px", // 设置列宽

        },
        {
            title: "入科评分",
            key: "Earliest_ScoreNumber",
            width: "100px", // 设置列宽

        },
        {
            title: "入科评分人",
            key: "Earliest_FULLNAME ",
            width: "140px", // 设置列宽

        },
        {
            title: "出科评分",
            key: "Latest_ScoreNumber",
            width: "100px", // 设置列宽

        },
        {
            title: "出科评分人",
            key: "Latest_SCOREMAN",
            width: "140px", // 设置列宽

        },
        {
            title: "死亡率",
            key: "Earliest_ScoreContent",
            width: "100px", // 设置列宽

        },
    ]
});

const { selectedYear, tableData, loading, headers } = toRefs(state);

onMounted(() => {
    // getTableData();
});


function formatTableData(rawData) {
    // 遍历原始数据，处理每一条记录
    return rawData.map(item => {
        const formattedItem = {};
        headers.value.forEach(header => {
            const key = header.key.trim(); // 去除 key 前后空格（避免 headers 配置误加空格）
            // 获取原始值：不存在则为 ''，存在且为 null/undefined 也转为 ''
            const rawValue = item.hasOwnProperty(key) ? item[key] : '';
            formattedItem[key] = rawValue === null || rawValue === undefined ? '' : rawValue;
        });
        formattedItem.INTIME = dayjs(formattedItem.INTIME).format("YYYY-MM-DD HH:mm:ss");
        return formattedItem;
    });
}

const handleYearChange = () => {
    getTableData()
};

// 导出Excel并选择保存位置
async function exportToExcel(data, fileName = '数据导出.xlsx') {
    // 创建自定义表头映射
    const headerMap = {
        "入科时间": "INTIME",
        "入科后X小时(h)": "system",
        "姓名": "NAME",
        "性别": "SEX",
        "年龄(岁)": "AGE",
        "床号": "BedName",
        "住院号": "AdmissionNumber",
        "入科评分": "Earliest_ScoreNumber",
        "入科评分人": "Earliest_FULLNAME",
        "出科评分": "Latest_ScoreNumber",
        "出科评分人": "Latest_SCOREMAN",
        "死亡率": "Earliest_ScoreContent",
    };

    // 转换数据格式以匹配自定义表头
    const exportData = data.map(item => {
        const newItem = {};
        Object.keys(headerMap).forEach(key => {
            const fieldKey = headerMap[key];
            // 如果headers中定义了key，则使用对应的数据字段
            const header = headers.value.find(h => h.title === key);
            if (header && header.key && item[header.key] !== undefined) {
                newItem[key] = item[header.key];
            } else {
                // 否则尝试使用原始键名
                newItem[key] = item[fieldKey] || '';
            }
        });
        return newItem;
    });

    // 添加表头行
    const ws = XLSX.utils.json_to_sheet(exportData, { header: Object.keys(headerMap) });

    // 设置列宽
    const colWidths = Object.keys(headerMap).map(key => ({ wch: key.length + 5 }));
    ws['!cols'] = colWidths;

    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'APACHEII评分');
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([wbout], { type: 'application/octet-stream' });
    // 创建 FormData 对象
    // const formData = new FormData();
    // formData.append("file", blob, "APACHEII评分.xlsx");
    // await uploadAPI(formData, 12578);

    // return

    if ('showSaveFilePicker' in window) {
        try {
            const fileHandle = await window.showSaveFilePicker({
                suggestedName: fileName,
                types: [{
                    description: 'Excel文件',
                    accept: { 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'] }
                }]
            });
            const writable = await fileHandle.createWritable();
            await writable.write(blob);
            await writable.close();
            return { success: true, message: '文件已成功保存' };
        } catch (error) {
            console.error('保存文件时出错:', error);
            // 继续使用回退下载方式
        }
    }

    // 回退下载方式
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    return { success: true, message: '文件已开始下载' };
}

// 导出
const handleExportExcel = async () => {
    const result = await exportToExcel(tableData.value, `${selectedYear.value[0]}-${selectedYear.value[1]}疾病统计.xlsx`);
    alert(result.message);
};
const getTableData = async () => {
    let data = {
        startDay: selectedYear.value[0],
        endDay: selectedYear.value[1]
    }
    const res = await getApacheAPI(data);
    tableData.value = formatTableData(res);
};

</script>

<style scoped>
.table-container {
    width: 1200px;
    height: 100%;
    position: relative;
}

.operate {
    display: flex;
    margin-bottom: 20px;
}

.bordered-table {
    border-collapse: collapse;
    border: 1px solid #13629a;
    width: 100%;
}


.bordered-table th,
.bordered-table td {
    border: 1px solid #13629a;
    box-sizing: border-box;
    padding: 10px;
}

.header {
    background: #0573c2;
    color: white;
}


.bordered-table th {
    font-size: 13px;
}

#printTable {
    width: 100%;
    min-height: 90vh;
    position: relative;
}
</style>